package io.github.eric.urpc.standalone.client;

import io.github.eric.urpc.client.Client;
import io.github.eric.urpc.client.ClientConfig;
import io.github.eric.urpc.core.util.RandomStringGenerator;
import io.github.eric.urpc.standalone.common.msg.IMMessage;
import io.github.eric.urpc.standalone.common.msg.UserLogin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class Application {
    private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
    private static List<MobileDevice> MOBILE_DEVICES = new ArrayList<>();

    public static void main(String[] args) {
        startStressTest(args);

//        sendMessageManually();
    }

    private static void startStressTest(String[] args) {
        int count = 100;
        if (args != null && args.length > 0) {
            count = Integer.parseInt(args[0]);
        }
        for (int i = 0; i < count; i++) {
            MobileDevice mobileDevice = new MobileDevice();
            MOBILE_DEVICES.add(mobileDevice);
        }
    }

    private static void sendMessageManually() {
        ClientConnListener clientConnListener = new ClientConnListener();
        ClientRpcController clientRpcController = new ClientRpcController();

        ClientConfig clientConfig = new ClientConfig.Builder()
//                .nettyLoggingLevel(LogLevel.INFO)
                .applicationName("mobile-device")
                .serverHost("127.0.0.1")
                .serverPort(52379)
                .heartBeatInterval(5)
                .connectionListeners(Collections.singletonList(clientConnListener))
                // set controllers
                .rpcControllers(Collections.singletonList(clientRpcController))
                .build();

        // init client and connect to server
        Client client = new Client(clientConfig);

        String applicationName = client.getClientConfig().getApplicationName();
        String applicationId = client.getClientConfig().getApplicationId();
        String userId = "User-" + applicationId;
        String userName = RandomStringGenerator.genRandomString(4);

        clientConnListener.setUserId(userId);
        clientConnListener.setUserId(userName);
        clientRpcController.setUserId(userId);
        clientRpcController.setUserName(userName);

        UserLogin userLogin = new UserLogin();
        userLogin.setUserId(userId);
        userLogin.setUserName(userName);
        client.sendAsync(userLogin);

        LOGGER.info("我的UserId是{}, userName是{}", userLogin.getUserId(), userLogin.getUserName());

        // 创建一个Scanner对象用于接收从控制台的输入
        Scanner scanner = new Scanner(System.in);

        System.out.println("欢迎来到控制台交互程序！请输入信息（输入'quit'以结束程序）：");

        // 循环等待用户输入
        while (true) {
            System.out.println("请输入要发送的信息，按 用户id@消息内容 的格式，例如 zhangsan@你在吗？");
            // 读取一行输入
            String userInput = scanner.nextLine();

            // 检查用户是否输入了退出命令
            if ("quit".equals(userInput)) {
                System.out.println("感谢使用，再见！");
                break;
            }

            String[] arr = userInput.split("@");
            if (arr.length != 2) {
                System.out.println("格式不对，忽略此次输入");
                continue;
            }
            String toUserId = arr[0];
            String content = arr[1];
            IMMessage imMessage = new IMMessage();
            imMessage.setMessageId(userId + "-" + UUID.randomUUID());
            imMessage.setFromUserId(userId);
            imMessage.setToUserId(toUserId);
            imMessage.setContent(content);
            LOGGER.info("向{}发消息: {}", toUserId, content);
            client.sendAsync(imMessage);

            // 回显用户输入的信息
//            System.out.println("程序回显：" + userInput);
        }

        // 关闭scanner对象，避免资源泄露
        scanner.close();
        System.exit(0);
    }
}